package com.qk.management.task;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.qk.common.util.AliYunOSSOperators;
import com.qk.entity.Image;
import com.qk.entity.User;
import com.qk.management.mapper.ImageMapper;
import com.qk.management.mapper.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.List;

@Component
@SuppressWarnings("all")
public class ImageDeleteTask {
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private ImageMapper imageMapper;
    @Autowired
    private AliYunOSSOperators oss;

    // 当前时间往前推 24 小时
    LocalDateTime twentyFourHoursAgo = LocalDateTime.now().minusHours(24);
    LocalDateTime tenMinutesAgo = LocalDateTime.now().minusMinutes(10);

//    @Scheduled(cron = "0 0 0/1 * * ?")
    @Scheduled(cron = "0 0 0 * * ?")
    public void clean(){

        //只查询24小时内更新的数据
        // 构造查询条件：update_time >= 24 小时前，且 <= 现在

        //查询 用户
        LambdaQueryWrapper<User> wrapper1 = new LambdaQueryWrapper<>();
        wrapper1.ge(User::getUpdateTime, twentyFourHoursAgo)  // >= 24 小时前
                .le(User::getUpdateTime, LocalDateTime.now()); // <= 当前时间
        userMapper.selectList( wrapper1);
        List<User> users = userMapper.selectList( wrapper1);
        //查询 图片
        LambdaQueryWrapper<Image> wrapper2 = new LambdaQueryWrapper<>();
        wrapper2.ge(Image::getCreateTime, twentyFourHoursAgo)
                .le(Image::getCreateTime, LocalDateTime.now());
        List<Image>  images = imageMapper.selectList( wrapper2);
        //遍历图片
        images.forEach(image -> {
            // 跳过10分钟内上传的图片，可能用户只是上传后卡住了还没点提交
            if (image.getCreateTime().isAfter(tenMinutesAgo)) {
                return; // 跳过当前图片
            }

            //图标表的url与用户表做对比，用户表存在的不删除，用户表不存在的删除
            if(!isinDB(image,users)){
                try {
                    oss.delete(image.getUrl().replaceAll(".*/", ""));
                    imageMapper.deleteById(image.getId());
                } catch (Exception e) {
                    throw new RuntimeException(e);
                }
            }
        });
    }

    //负责查找用户表是否有图片与这个image图片的url对应
    public static boolean isinDB(Image  image,List<User>  users){
        boolean exist = false;
        for (User user : users) {
            if (ObjectUtil.equal(image.getUrl(), user.getImage())) {
                exist = true;
                break;
            }
        }
        return exist;
    }

}
